import Vue from 'vue';
//1.引入vue-router
import VueRouter from 'vue-router';

import Type from '../pages/type.vue';
import Home from '../pages/Home.vue';
import Vip from '../pages/Vip.vue';
import Car from '../pages/Car.vue';
import Err from '../pages/Err.vue';
import List from '../pages/List.vue';
import Mine from '../pages/Mine.vue';
import Detail from '../pages/Detail.vue';
import Reg from '../pages/Reg.vue';
import Logout from '../pages/Logout.vue';
import UpdatePsw from '../pages/updatePsw.vue';

//2.使用vue-router（script标签引入方式自动完成）
Vue.use(VueRouter);

const router = new VueRouter({
    routes: [{
        name: 'type',
        path: '/type',
        component: Type
    }, {
        name: 'home',
        //当浏览器地址为/home时，显示Home组件的内容
        path: '/home',
        component: Home
    }, {
        name: '',
        path: '/',
        component: Home
        //重定向
        // redirect: Home
    }, {
        name: 'vip',
        path: '/vip',
        component: Vip
    }, {
        name: 'car',
        path: '/car',
        component: Car,
        meta: {
            requiresAuth: true
        }
    }, {
        name: 'mine',
        path: '/mine',
        component: Mine,
        meta: {
            requiresAuth: true
        }
    }, {
        name: 'list',
        path: '/list',
        component: List
    },
    {
        name: 'detail',
        path: '/detail',
        component: Detail
    },
    {
        name: 'logout',
        path: '/logout',
        component: Logout
    }, {
        name: 'reg',
        path: '/reg',
        component: Reg
    }, {
        name: 'updatePsw',
        path: '/updatePsw',
        component: UpdatePsw
    }, {
        name: '404',
        path: '*',
        component: Err
    }
    ]
})

import Api from '../Api/index';
import qs from "qs";
// 全局路由守卫
router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth) {
        // 获取token
        let Authorization = localStorage.getItem('Authorization');
        if (Authorization) {
            next();
            // 发送校验请求
            Api.my
                .post('/verify', qs.stringify({
                    token: Authorization
                }))
                .then(res => {
                    if (res.data.code === 0) {
                        next({
                            path: '/reg',
                            query: {
                                redirectUrl: to.fullPath
                            }
                        });
                    }
                });
        } else {
            next({
                path: '/reg',
                query: {
                    redirectUrl: to.path
                }
            });
        }

    } else {
        next();
    }
})

export default router